package com.itheima.filter;

import com.itheima.bean.Employee;
import com.itheima.bean.User;
import com.itheima.utils.BaseContext;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
    登录校验过滤器
        1. 创建过过滤器

        2. 配置过滤器  @WebFilter("/*")

        3. 要在启动类上打注解 @ServletComponentScan注解，否则这个过滤器不生效！
 */
@Component
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //1. 获取当前请求的地址
        //  /backend/index.html
        String uri = req.getRequestURI();

        //  http://localhost:8080/backend/index.html
        //StringBuffer requestURL = req.getRequestURL();

        //2. 判断地址是否属于免登录直接放行的地址
        if(uri.contains("login") || uri.endsWith(".js") || uri.contains("images") || uri.contains("plugins")
            || uri.contains("styles") || uri.endsWith(".ico") || uri.contains("sms")){
            //2.1 如果是，那么直接放行！
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //2.2 如果不是，那么即表示这个请求需要校验登录。
        Employee employee = (Employee) req.getSession().getAttribute("employee");

        //3. 判断用户有没有登录...
        if(employee != null){
            //3.0 在这里已经确保这个员工是登录的，所以把员工的id保存到ThreadLocal里面去
            BaseContext.setCurrentId(employee.getId());

            //3.1 如果有，即表示已经登录，那么直接放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //3. 判断是否有登录了前端
        User user = (User) req.getSession().getAttribute("user");
        if(user != null){
            BaseContext.setCurrentId(user.getId());
            //3.1 如果有，即表示已经登录，那么直接放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //3.2 如果没有，表示还没有登录，那么跳转到登录页面去！
        if(uri.contains("backend")){
            resp.sendRedirect("/backend/page/login/login.html");
        }else{
            resp.sendRedirect("/front/page/login.html");

        }

    }
}
